/*
 *  Copyright (C) 2011 Karthick Selvaraj.
 * 
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package com.cyrph.rednylon;

import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.BoundedRangeModel;
import javax.swing.JPanel;
import org.openide.WizardDescriptor;
import org.redmine.ta.AuthenticationException;
import org.redmine.ta.NotFoundException;
import org.redmine.ta.RedmineException;
import org.redmine.ta.RedmineManager;

public final class SiteUserSetupVisualPanel2 extends JPanel {

    /** Creates new form SiteUserSetupVisualPanel2 */
    public SiteUserSetupVisualPanel2() {
        initComponents();
        init();
    }

    @Override
    public String getName() {
        return "Finish";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jProgressBar1 = new javax.swing.JProgressBar();
        jButton1 = new javax.swing.JButton();
        urlPreview = new javax.swing.JLabel();
        previewAPI = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(SiteUserSetupVisualPanel2.class, "SiteUserSetupVisualPanel2.jButton1.text")); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                jButton1MouseMoved(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(urlPreview, org.openide.util.NbBundle.getMessage(SiteUserSetupVisualPanel2.class, "SiteUserSetupVisualPanel2.urlPreview.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(previewAPI, org.openide.util.NbBundle.getMessage(SiteUserSetupVisualPanel2.class, "SiteUserSetupVisualPanel2.previewAPI.text")); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(urlPreview)
                    .addComponent(previewAPI)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(317, 317, 317)
                        .addComponent(jButton1))
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(urlPreview)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(previewAPI)
                .addGap(69, 69, 69)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        if (jButton1.isEnabled()) {
            jButton1.setEnabled(false);
            jProgressBar1.setVisible(true);
            displayMessage("Testing the settings...");
            testSettings();
            jButton1.setEnabled(true);
        }
    }//GEN-LAST:event_jButton1MouseClicked

    private void jButton1MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseMoved
        if(!jButton1.isEnabled())
        {
            jProgressBar1.setVisible(true);
        }
    }//GEN-LAST:event_jButton1MouseMoved

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel previewAPI;
    private javax.swing.JLabel urlPreview;
    // End of variables declaration//GEN-END:variables

    public void init() {
        jProgressBar1.setVisible(false);
        jTextArea1.setEditable(true);
        jTextArea1.setText("Press \"test\" to test the below settings.");
        jProgressBar1.setIndeterminate(true);
    }

    private void displayMessage(String message)
    {
        jTextArea1.setEditable(true);
        jTextArea1.setText(message);
        jTextArea1.setEditable(false);
    }
    private boolean valid = false;

    public boolean isTestValid() {
        return valid;
    }
    private boolean finished = false;

    public boolean isFinished() {
        return finished;
    }
    private String message = "Unknown internal error.";

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
        displayMessage(message);
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public void setFinished(boolean finished) {
        jProgressBar1.setVisible(false);
        this.finished = finished;
    }
    String urlString = "";
    String apiString = "";

    public void testSettings(String url, String api) {
        apiString = api;
        urlString = url;
        init();
        setFinished(false);
        setValid(false);
        jButton1.setEnabled(true);
        previewAPI.setText("API: " + api);
        urlPreview.setText("URL: " + url);
    }

    private void testSettings() {
        boolean nfe = false, ioe = false, ae = false, rede = false, rte = false;
        try {
            RedmineManager rmm = new RedmineManager(urlString, apiString);
            rmm.getProjects();
        } catch (NotFoundException ex) {
            nfe = true;
            setMessage("404 Not Found, Could not connect to server: " + urlString);
            //Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            ioe = true;
            setMessage("Could not connect to server: " + urlString);
            //Exceptions.printStackTrace(ex);
        } catch (AuthenticationException ex) {
            ae = true;
            setMessage("The user API key: " + apiString + " is invalid.");
            //Exceptions.printStackTrace(ex);
        } catch (RedmineException ex) {
            rede = true;
            setMessage("There is an error in Redmine.");
            //Exceptions.printStackTrace(ex);
        } catch (RuntimeException ex) {
            rte = true;
            setMessage(ex.getMessage());
        }
        setFinished(true);

        if (!nfe && !ioe && !ae && !rede && !rte) {
            displayMessage("The URL is appeared to be valid. Note that the API will be stored will be checked \nwhen you are trying to perform priviliged actions like Create, Delete or Update.");
            setValid(true);
        }
    }
}

